/**
 * Created by jiachneyu on 2018/4/20.
 */
const db = require('../../db');
const collection = db.get('blog');

const find = async (sql, params) => {
    return await collection.find(sql, params).then(res => {
        if (res) {
            db.close();
            return {
                code: 1,
                data: res
            }
        }
    }).catch(err => {
        console.log(err);
        db.close();
        return {
            code: -1
        }
    })
}

const findOne = async (sql, params) => {
    return await collection.findOne(sql, params).then(res => {
        console.log(res)
        if (res) {
            return {
                code: 1,
                data: res
            }
        }
        else {
            return {
                code: -1,
            }
        }
    }).catch(err => {
        db.close();
        return {
            code: -1
        }
    })
}

const insert = async (data) => {
    return await collection.insert(data).then(res => {
        console.log(res);
        if (res) {
            db.close();
            return {
                code: 1,
            }
        }
    }).catch(err => {
        db.close();
        return {
            code: -1
        }
    })
}

const update = async (o, n) => {
    return await collection.update(o, n).then(res => {
        if (res) {
            db.close();
            return {
                code: 1,
            }
        }
    }).catch(err => {
        db.close();
        return {
            code: -1
        }
    })
}

const findAndUpdate = async (query, update) => {
    return await collection.findOneAndUpdate(query, update).then(res => {
        if (res) {
            db.close();
            return {
                code: 1,
                data: res
            }
        }
    }).catch(err => {
        db.close();
        return {
            code: -1
        }
    })
}

const remove = async (query) => {
    return await  collection.remove(query).then(res => {
        console.log(res)
        db.close();
        if (res.result.n === 1 && res.result.ok === 1) {
            return {
                code: 1,
                data: res
            }
        }
        else {
            return {
                code: -1
            }
        }
    }).catch(err => {
        db.close();
        return {
            code: -1
        }
    })
}


module.exports = {
    find: find,
    findOne: findOne,
    insert: insert,
    update: update,
    findAndUpdate: findAndUpdate,
    remove
};